<?php

namespace App\Models\Activity\Jd;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\Redis as Redis;

class Jd extends Model
{

    protected $table = 'jd';

    protected $primaryKey = 'activity_id';

    public $timestamps = false;

    public $incrementing = false;

    public static function getCache ( $id ) {

        $jd_cache = Redis::get('G_WDH_JD_' . $id );

        if ( empty( $jd_cache ) ) {

            $jd = self::find($id);
            if ( empty( $jd ) ) {
                return null;
            }

            $jd->extend_json = json_decode( $jd->extend_json ,true );

            $jd_cache = $jd->toArray();

            Redis::setex( 'G_WDH_JD_' . $id , 604800 , json_encode($jd_cache) );

        } else {
            $jd_cache = json_decode( $jd_cache , true );
        }

        return $jd_cache;

    }

    //获取领取数量
    public static function getReceiveNum ( $id ) {

        $receive_num = Redis::get('G_WDH_JD_RECEIVE_NUM_' . $id  );
        if ( empty( $receive_num ) ) {

            $jd_cache = self::getCache( $id );

            if ( empty( $jd_cache ) ) {
                return -1;
            }

            $receive_num = $jd_cache['receive_num'];

            Redis::setex( 'G_WDH_JD_RECEIVE_NUM_' . $id , 604800 , $receive_num );
        }

        return $receive_num;

    }

    //更新领取数量
    public static function updateReceiveNum ( $id ) {

        $is_exists = Redis::exists('G_WDH_JD_RECEIVE_NUM_' . $id );
        if ( !$is_exists ) {
            $get_num = self::getReceiveNum($id);
            if ( $get_num < 0 ) {
                return -1;
            }
        }

        Redis::incr('G_WDH_JD_RECEIVE_NUM_' . $id ) ;

        return true;

    }

}